import React, { useEffect, useState } from 'react'
import axios from 'axios'

export default function App() {
  const [repo, setRepo] = useState({
    name: '',
    url: ''
  })

  // 初始化发一次请求
  useEffect(() => {
    // 注意: effect函数不能是async函数
    async function getRepo() {
      // 发请求
      const response = await axios.get(
        'https://api.github.com/search/repositories',
        {params: {q: 'v', sort: 'stars'}}
      )
      // 请求成功后, 读取数据
      const result = response.data
      const {name, html_url} = result.items[0]
      // 更新状态数据
      setRepo({
        name,
        url: html_url
      })
    }

    getRepo()
  }, [])


  if (repo.name) {
    return (
      <div>
        most star repo is <a href={repo.url}>{repo.name}</a>
      </div>
    )
  } else { // 显示loading界面
    return <h2>LOADING...</h2>
  }
}
